<?php

namespace app\controller\wmapi\order;

use App\Library\Y;
use app\model\WaAdmins;
use app\model\WaMembers;
use app\model\WaOrders;
use app\model\WaOrdersQuotation;
use app\model\WaOrdersQuotationOperateLog;
use app\model\WaOrdersQuotationRelevance;
use app\model\WaOrdersQuotationAmountDetail;
use app\controller\wmapi\IndexController;
use app\model\WaOrdersRelevance;
use app\model\WaProducts;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\controller\Crud;
use plugin\admin\app\model\User;
use support\Request;
use support\Response;
use Tinywan\Validate\Validate;
use Workerman\Worker;

class OrderQuotationController extends Validate
{
    /**
     * 创建报价单
     * @param Request $request
     * @return Response
     * 订单创建人->下单用户->下了几款车型笔->多少量->从哪里发到哪里->中间产生了多少费用
     */
    public function createQuotationOrder(Request $request)
    {
        // 验证用户登录
        //  process($request);

        // 获取参数信息
        $param = $request->all();

        //车型信息
        $specs = $param['specs_can'];

        // 获取管理员信息
        $adminId = json_decode(adminId($request));

        // 必传参数验证
        $order_quotation_add = OrderQuotationController::validateAdd($param, $adminId);
        if ($order_quotation_add != 'true') {

            return IndexController::errored('', $order_quotation_add);
        }
        //验证车型入参
        $specs_can_add = OrderQuotationController::validateSpecsCan($param['specs_can'], $dataSelect);
        if ($specs_can_add != 'true') {
            return IndexController::errored('', $specs_can_add);
        }

        // 今天开始时间
        $todayStart = strtotime("today");
// 今天结束时间
        $todayEnd = strtotime("tomorrow") - 1;
//获取当前用户今日的订单数量 ;
        $admin_order_count_todady = WaOrdersQuotation::quotationOrdersCountByAdmin($todayStart,$todayEnd,$adminId);
        $admin_order_count_todady = $admin_order_count_todady + 1;
        if ($admin_order_count_todady < 10){
            $admin_order_count_todady = str_pad($admin_order_count_todady, 2, '0', STR_PAD_LEFT); // 使用str_pad添加0
        }
        if (!$adminId->nickname_abbreviation){
            $adminId->nickname_abbreviation = 'TS'.$adminId->id;
        }


        // 创建销售订单 父订单编号
        $quotation_order_sn = 'WMQ' . IndexController::generateOrderSn(). $adminId->nickname_abbreviation.$admin_order_count_todady;

        //订单数据
       OrderQuotationController::order_data_by_create($quotation_order_sn,$param,$adminId,$dataSelect,$order_data);


        if ($specs) {
            \support\Db::beginTransaction();
            try {
                $orders_id = WaOrdersQuotation::created($order_data); // 创建报价单
                if (!$orders_id) {
                    return IndexController::errored('', '创建报价单失败');
                }

                foreach ($specs as $k) {
                    $order_sn_child = 'WMBJZ' . IndexController::generateOrderSnOther(); // 子订单编号
                    // 创建子订单数据
                   $order_detail_add =  OrderQuotationController::order_detail_data_create($quotation_order_sn,$order_sn_child,$k,$orders_id, $adminId);
                    if (!$order_detail_add) {
                        return IndexController::errored('', '创建报价单产品信息失败');
                    }
                }

                //添加报价单账单明细
               $bill_details_create =  OrderQuotationController::bill_details_create($quotation_order_sn,$param,$adminId);
                if ($bill_details_create != 'true') {
                    return IndexController::errored('', $bill_details_create);
                }
                // 报价单操作日志添加
                $describe = $adminId->nickname.'创建报价单表新数据';
                $status = 0; // 报价单状态 0 草稿 1 待客户确认 2 代下单 3 已完成 4已作废 5删除
                $operate_log_add = OrderQuotationController::operateLogAdd($quotation_order_sn,$status,$adminId,$describe);
                if ($operate_log_add != 'true') {
                    return IndexController::errored('', $operate_log_add);
                }

                \support\Db::commit();
                return IndexController::successed('', '报价单创建成功');
            } catch (\Throwable $exception) {

                IndexController::logError('createQuotationOrder', $param, $adminId, $exception);

                // 回滚
                \support\Db::rollBack();

                return IndexController::errored($exception, '报价单创建失败');
            }

        } else {
            return IndexController::errored($specs, '创建报价单失败，参数值为空');
        }


    }

    // 主订单入参验证-create
    public static function validateAdd($param, $adminId)
    {
        $rule = [
            'admin_id' => 'require|max:20',
            'pol' => 'require',
            'pod' => 'require',
            'condition' => 'require',
            'specs_can' => 'require|array',
        ];

        $validate = \Tinywan\Validate\Facade\Validate::rule($rule);

        // 必传参数
        $data = [
            'admin_id' => $adminId->id, // 创建人id
            'pol' => $param['pol'], // 装货港
            'pod' => $param['pod'], // 卸货港
            'condition' => $param['condition'], // 交货条件
            'specs_can' => $param['specs_can'], // 产品参数
        ];
        if (array_key_exists('pol_en',$param)){
            $data['pol_en'] = $param['pol_en'];
        }
        if (array_key_exists('pod_en',$param)){
            $data['pod_en'] = $param['pod_en'];
        }

        if (!$validate->check($data)) {
            return '创建报价单入参有误';
        }
        return 'true';
    }

    // 子订单入参验证-create
    public static function validateSpecsCan($specs,&$dataSelect)
    {

        $rule = [
            'brands_name' => 'require',
            'series_name' => 'require',
            'model' => 'require',
            'guide_price' => 'require',
            'count' => 'require',
        ];

        // 用于列表查询的数据
        $dataSelect = [
            'brands_name' => '',
            'series_name' => '',
            'model' => '',
            'sub_brand_name' => '',
            'including_model' => [],
        ];

        foreach ($specs as $k) {
            $dataSelect['brands_name'] =  $dataSelect['brands_name'] . ' / ' . $k['brands_name'];
            $dataSelect['series_name'] =  $dataSelect['series_name'] . ' / ' . $k['series_name'];
            $dataSelect['model'] =  $dataSelect['model'] . ' / ' . $k['model'];
            $dataSelect['sub_brand_name'] =  $dataSelect['sub_brand_name'] . ' / ' . $k['sub_brand_name'];
            $including_model =  $k['brands_name'].'/'.$k['sub_brand_name'].'/'.$k['series_name'].'/'.$k['model'];
            array_push($dataSelect['including_model'],$including_model);
        }

        if($dataSelect['including_model']){
            $dataSelect['including_model'] = json_encode($dataSelect['including_model']);
        }

        return 'true';
    }

    // 订单创建数据-create

    public static function order_data_by_create($quotation_order_sn,$param,$adminId,$dataSelect,&$order_data){
        $order_data = [
            'quotation_order_sn' => $quotation_order_sn,
            'pol' => $param['pol'], // POL装港
            'pod' => $param['pod'], // POD卸港
            'cnh' => $param['cnh'], // 美元汇率
            'condition' => $param['condition'], // 交货条件

            'status' => 0, //报价单状态 0 草稿 1 待客户确认 2 待下单 3 已完成 4 删除 5作废
            'created_at' => date('y-m-d h:m:s', time()), // 创建时间
            'admin_id' => $adminId->id, // 管理员名称
            'admin_name' => $adminId->nickname, // 管理员名称
            'currency' => $param['currency'], // 货币类型   1人民币 2 美元 3 欧元
            'shipment' => $param['shipment'], // 1 汽运、2 铁路、海运(3 集装箱、4滚装船)

        ];
        $order_data['brands_name'] =  $dataSelect['brands_name'];
        $order_data['series_name'] =  $dataSelect['series_name'];
        $order_data['model'] =  $dataSelect['model'];
        $order_data['sub_brand_name'] =  $dataSelect['sub_brand_name'];
        $order_data['including_model'] =  $dataSelect['including_model'];

        if (array_key_exists('pol_en',$param)){
            $order_data['pol_en'] = $param['pol_en'];
        }
        if (array_key_exists('pod_en',$param)){
            $order_data['pod_en'] = $param['pod_en'];
        }
        // 判断开始时间
        if (array_key_exists('exp_start_time',$param)){
            $order_data['exp_start_time'] = $param['exp_start_time'];
        }
        // 判断过期时间
        if (array_key_exists('exp_end_time',$param)){
            $order_data['exp_end_time'] = $param['exp_end_time'];
        }
        // 判断总毛利(溢价)
        if (array_key_exists('total_premium_price',$param)){
            $order_data['total_premium_price'] = $param['total_premium_price'];
        }

        // 判断总毛利(溢价)
        if (array_key_exists('total_amount',$param)){
            $order_data['total_amount'] = $param['total_amount'];
        }


    }

    // 子订单数据-create
    public static function order_detail_data_create($quotation_order_sn,$order_sn_child,$k,$orders_id, $adminId){
        $order_detail_data = [
            'order_sn_parent' => $quotation_order_sn, // 父订单编号
            'order_sn_child' => $order_sn_child, // 子订单编号
            'brands_name' => $k['brands_name'], // 品牌
            'series_name' => $k['series_name'], // 车系
            'model' => $k['model'], // 车型名称
            'is_nev' => $k['is_nev'], // 是否新能源 1 是 2 传统能源
            'market_time' => $k['market_time'], // 上市日期
            'vehicle_status' => $k['vehicle_status'] ? round($k['vehicle_status'], 2) : 0, // 车辆状况(是否是新车)  1 新车 2 二手车
            'guide_price' => $k['guide_price'] ? round($k['guide_price'], 2) : 0, // 指导价
            'option_package' => json_encode($k['option_package']), // 选装包
            'traffic_compulsory_insurance' => $k['traffic_compulsory_insurance'] ? round($k['traffic_compulsory_insurance'], 2) : 0, // 交强险
            'premium_price' => $k['premium_price'] ? round($k['premium_price'], 2) : 0, //  溢价
            'final_offer_price' => $k['final_offer_price'] ? round($k['final_offer_price'], 2) : 0, //  最终报价 / 报价单价
            'port_departure_charges' => $k['port_departure_charges'] ? round($k['port_departure_charges'], 2) : 0, // 起运港港杂费
            'international_freight' => $k['international_freight'] ? round($k['international_freight'], 2) : 0, // 国际运费
            'count' => $k['count'] ? round($k['count'], 2) : 0, // 数量
            'created_at' => date('y-m-d h:m:s', time()), // 创建时间
            'sub_brand_name' => $k['sub_brand_name'], // 厂商
            'purchase_quotation' => $k['purchase_quotation'] ? round($k['purchase_quotation'], 2) : 0, // 行情报价
            'purchase_price' => $k['purchase_price'] ? round($k['purchase_price'], 2) : 0, // 二手车采购价格
            'VAT_invoice_price' => $k['VAT_invoice_price'] ? round($k['VAT_invoice_price'], 2) : 0, // 增值税发票金额
            'retail_concessions' => $k['retail_concessions'] ? round($k['retail_concessions'], 2) : 0, // 零售优惠
            'other_rebates' => $k['other_rebates'] ? round($k['other_rebates'], 2) : 0, // 采购返利
            'registration_fee' => $k['registration_fee'] ? round($k['registration_fee'], 2) : 0, //  上牌费用
            'used_car_fee' => $k['used_car_fee'] ? round($k['used_car_fee'], 2) : 0, //  二手车过户费用
            'transfer_export_fee' => $k['transfer_export_fee'] ? round($k['transfer_export_fee'], 2) : 0, // 转移待出口费用
            'total_price' => $k['total_price'] ? round($k['total_price'], 2) : 0,
            'premium_charges' => $k['premium_charges'] ? round($k['premium_charges'], 2) : 0,// 国际运输保险费
            'price_options' => json_encode($k['price_options']), // 费用选项
            'seat_count' => $k['seat_count'], // 座位数
            'car_year' => $k['car_year'], //  车辆年款
            'jb' => $k['jb'], // 级别
            'series_type' => $k['series_type'], // 车身类型
            'driver_form' => $k['driver_form'], // 驱动方式
            'length' => $k['length'], // 长
            'width' => $k['width'], // 宽
            'height' => $k['height'], // 高
            'curb_weight' => $k['curb_weight'], // 设计重量
            'resource_service_fee' => $k['resource_service_fee'], // 资源服务费

        ];
        if (array_key_exists('urban_trailer_fee',$k)){
            $order_detail_data['urban_trailer_fee'] = $k['urban_trailer_fee'] ? round($k['urban_trailer_fee'], 2) : 0; // 城区拖车费
        }

        if (array_key_exists('domestic_storage_fees',$k)){
            $order_detail_data['domestic_storage_fees'] = $k['domestic_storage_fees'] ? round($k['domestic_storage_fees'], 2) : 0; // 国内仓储费
        }

        if (array_key_exists('car_wash_beauty_fee',$k)){
            $order_detail_data['car_wash_beauty_fee'] = $k['car_wash_beauty_fee'] ? round($k['car_wash_beauty_fee'], 2) : 0; // 洗车美容费
        }

        if (array_key_exists('used_car_check_fee',$k)){
            $order_detail_data['used_car_check_fee'] = $k['used_car_check_fee'] ? round($k['used_car_check_fee'], 2) : 0; // 二手车检测费/第三方检测费
        }

        if (array_key_exists('port_price',$k)){
            $order_detail_data['port_price'] = $k['port_price'] ? round($k['port_price'], 2) : 0; // 集港物流费
        }

        if (array_key_exists('export_testing_fee',$k)){
            $order_detail_data['export_testing_fee'] = $k['export_testing_fee'] ? round($k['export_testing_fee'], 2) : 0; // 出口检测费
        }

        if (array_key_exists('color_interior',$k)){
            $order_detail_data['color_interior'] = $k['color_interior']; // 内饰颜色
        }
        if (array_key_exists('color_exterior',$k)){
            $order_detail_data['color_exterior'] = $k['color_exterior']; // 外观颜色
        }

        if (array_key_exists('model_en',$k)){
            $order_detail_data['model_en'] = $k['model_en']; // 车型
        }
        if (array_key_exists('series_name_en',$k)){
            $order_detail_data['series_name_en'] = $k['series_name_en']; // 车系
        }
        if (array_key_exists('brands_name_en',$k)){
            $order_detail_data['brands_name_en'] = $k['brands_name_en']; // 品牌
        }
        if (array_key_exists('fuel_form_en',$k)){
            $order_detail_data['fuel_form_en'] = $k['fuel_form_en']; // 能源类型
        }
        if (array_key_exists('color_interior_en',$k)){
            $order_detail_data['color_interior_en'] = $k['color_interior_en']; // 内饰颜色
        }
        if (array_key_exists('color_exterior_en',$k)){
            $order_detail_data['color_exterior_en'] = $k['color_exterior_en']; // 外观颜色
        }
        if (array_key_exists('sub_brand_name_en',$k)){
            $order_detail_data['sub_brand_name_en'] = $k['sub_brand_name_en']; // 厂商
        }
        if (array_key_exists('is_drawback',$k)){
            $order_detail_data['is_drawback'] = $k['is_drawback']; // 是否退税
        }
        if (array_key_exists('is_CLIVTA',$k)){
            $order_detail_data['is_CLIVTA'] = $k['is_CLIVTA']; // 是否交强险  文森说的 要大些
        }
        if (array_key_exists('invoice_price',$k)){
            if ($k['invoice_price']){
                $order_detail_data['invoice_price'] = $k['invoice_price']; // 机动车专用发票价
            }
        }


        if (array_key_exists('other_price',$k)){
            if ($k['other_price']){
                $order_detail_data['other_price'] = json_encode($k['other_price']); // 其它费用
            }
        }
        $order_detail_data ['orders_id'] = $orders_id;
        $order_detail_id = WaOrdersQuotationRelevance::created($order_detail_data); // 创建订单详情
        if (!$order_detail_id) {
            return '创建报价单失败';
        }
        return true;
    }



    // 账单明细数据-all
    public static function bill_details_create($quotation_order_sn,$param,$adminId){
        $bill_details = $param['bill_details'];

        if ($bill_details) {
            foreach ($bill_details as $kd) {
                $bill_details_data = [
                    'quotation_order_sn' => $quotation_order_sn, //
                    'total_amount' => $kd['total_amount'], //
                    'price_name' => $kd['price_name'], //
                    'admin_id' => $adminId->id, //
                    'admin_name' => $adminId->nickname, //
                    'created_at' => dateTime(), //
                ];
                $bill_details_id = WaOrdersQuotationAmountDetail::created($bill_details_data); // 创建订单详情
                if (!$bill_details_id) {
                    return '添加订单账单明细失败';
                }
            }
        } else {
            return '采购费用，参数值为空';
        }
        return 'true';
    }


    /**
     * 更新报价单
     * @param Request $request
     * @return Response
     */
    public function updateQuotationOrder(Request $request)
    {

//        process($request);
        // 获取参数信息
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));



        if ($param['specs_can']) {
            \support\Db::beginTransaction();
            try {
                // 多状态参数验证
                $check_more_status = OrderQuotationController::checkMoreStatus($param,$adminId,$find);
                if ($check_more_status != 'true') {
                    return IndexController::errored('', $check_more_status);
                }
                // 主订单信息更新
                $order_data = [];
                //更改的字段
                $change_clounm = '';
                OrderQuotationController::orderDataByEdit($param,$find,$order_data,$change_clounm);


                //获取删除前的信息
                WaOrdersQuotationRelevance::delete(['order_sn_parent' => $param['order_sn_parent']]); // 删除之前创建的 添加新的数据

                //创建新的报价单详情数据
                $specs = $param['specs_can'];
                $order_detail_data = [];
                OrderQuotationController::order_data_by_edit($specs,$param,$order_detail_data,$order_data);

                // 更新报价单表信息
                $condition_quotation = [];
                $condition_quotation [] = ['quotation_order_sn','=', $param['order_sn_parent']];
                $ordersUp = WaOrdersQuotation::updated($order_data, $condition_quotation); // 更新报价单
                if (!$ordersUp) {
                    return IndexController::errored('', '报价单更新失败');
                }

                // 删除账单明细
                WaOrdersQuotationAmountDetail::deleted(['quotation_order_sn' => $param['order_sn_parent']]); // 创建订单详情
                //创建新的报价单账单明细
                $bill_details_create = OrderQuotationController::bill_details_create($param['order_sn_parent'],$param,$adminId);
                if ($bill_details_create != 'true') {
                    return IndexController::errored('', $bill_details_create);
                }
                \support\Db::commit();

                // 报价单操作日志添加
                // 报价单状态 0 草稿 1 待客户确认 2 代下单 3 已完成 4已作废 5删除
                $status =  $find->status;
                $clounm = $change_clounm;//暂未处理
                $describe = $adminId->nickname.'更新报价单表 wa_orders_quotation 字段'.$clounm.dateTime();
                $operate_log_add = OrderQuotationController::operateLogAdd($param['order_sn_parent'],$status,$adminId,$describe);
                if ($operate_log_add != 'true') {
                    return IndexController::errored('', $operate_log_add);
                }

                return IndexController::successed('', '订单更新成功');
            } catch (\Throwable $exception) {
//                echo $exception;
                IndexController::logError('updateQuotationOrder', $param, $adminId, $exception);

                // 回滚
                \support\Db::rollBack();

                // 抛出一个标准的异常

                return IndexController::errored($exception, '订单更新失败');
            }

        } else {
            return IndexController::errored('', '更新失败，参数值为空');
        }




    }
    // 多状态参数验证-edit
    public static function checkMoreStatus($param,$adminId,&$find){

        $find = WaOrdersQuotation::find(['quotation_order_sn' => $param['order_sn_parent']]);
        $find = json_decode($find);
        if (!$find) {
            return '订单状态查询失败';
        }
        $status = $find->status;
        // 报价单状态 0 草稿 1 待客户确认 2 待下单 3 已完成 4已作废 5删除
        if (!in_array($status, [0, 4])) {
            return '只有草稿和作废状态才能编辑';
        }
        if ($find->admin_id != $adminId->id) {
            return '只能编辑自己的报价单';
        }

        // 编辑验证
        $orders_find = WaOrders::find(['quotation_order_sn' => $param['order_sn_parent']]);
        $orders_find = json_decode($orders_find);
        if ($orders_find) {
            return '该报价单已生成销售订单,不能重新编辑';
        }
        return 'true';
    }

    // 主订单信息更新-edit
    public static function orderDataByEdit($param,$find,&$order_data,&$change_clounm){
        $order_data = [
            'pol' => $param['pol'], // POL装港
            'pod' => $param['pod'], // POD卸港
            'condition' => $param['condition'], // 交货条件
            'cnh' => $param['cnh'], // 美元汇率
            'currency' => $param['currency'], // 币种 1 人民币 2 美元 3 欧元
            'shipment' => $param['shipment'], // 1 汽运、2 铁路、海运(3 集装箱、4滚装船)
            'updated_at' => dateTime(), // 更新时间
        ];
        if ($find->status == 4){
            $order_data['status'] = 0;
        }

        if (array_key_exists('exp_start_time',$param)){
            $order_data['exp_start_time'] = $param['exp_start_time'];
        }

        if (array_key_exists('exp_end_time',$param)){
            $order_data['exp_end_time'] = $param['exp_end_time'];
        }
        if (array_key_exists('pol_en',$param)){
            $order_data['pol_en'] = $param['pol_en'];
        }
        if (array_key_exists('pod_en',$param)){
            $order_data['pod_en'] = $param['pod_en'];
        }
        // 判断总毛利(溢价)
        if (array_key_exists('total_premium_price',$param)){
            $order_data['total_premium_price'] = $param['total_premium_price'];
        }

        // 判断总毛利(溢价)
        if (array_key_exists('total_amount',$param)){
            $order_data['total_amount'] = $param['total_amount'];
        }

        // 被更新的字段
        $change_clounm = [];
        foreach ($order_data as $ko => $vo){
            foreach ($find as $kf => $vf){
                if ($ko == $kf){
                    if ($vo != $vf){
                        array_push($change_clounm,$kf);
                    }
                }
            }
        }
        if ($change_clounm){
            $change_clounm = json_encode($change_clounm);
        }
    }

    // 订单详情数据-edit
    public static function order_data_by_edit($specs,$param,&$order_detail_data,&$order_data){
        // 用于列表查询的数据
        $order_data['brands_name'] = '';
        $order_data['series_name'] =  '';
        $order_data['model'] =  '';
        $order_data['sub_brand_name'] =  '';
//        $order_data['transfer_export_province'] = '';
        $order_data['including_model'] = [];


        foreach ($specs as $k) {
            $order_sn_child = 'WMBJZ' . IndexController::generateOrderSnOther(); // 子订单编号
            $order_detail_data = [
                'order_sn_parent' => $param['order_sn_parent'], // 父订单编号
                'order_sn_child' => $order_sn_child, // 子订单编号
//                        'product_no' => $k['product_no'], // 关联产品编号
//                        'product_type' => $k['product_type'], // 产品类型
                'brands_name' => $k['brands_name'], // 品牌
                'series_name' => $k['series_name'], // 车系
                'model' => $k['model'], // 车型名称
                'is_nev' => $k['is_nev'], // 是否新能源 1 是 2 传统能源
                'market_time' => $k['market_time'], // 上市日期
                'vehicle_status' => $k['vehicle_status'] ? round($k['vehicle_status'], 2) : 0, // 车辆状况(是否是新车)  1 新车 2 二手车
                'guide_price' => $k['guide_price'] ? round($k['guide_price'], 2) : 0, // 指导价
                'option_package' => json_encode($k['option_package']), // 选装包
                'traffic_compulsory_insurance' => $k['traffic_compulsory_insurance'] ? round($k['traffic_compulsory_insurance'], 2) : 0, // 交强险
                'premium_price' => $k['premium_price'] ? round($k['premium_price'], 2) : 0, //  溢价
                'final_offer_price' => $k['final_offer_price'] ? round($k['final_offer_price'], 2) : 0, //  最终报价 / 报价单价
//                'registration_id' => $k['registration_id'] ? intval($k['registration_id']) : 0, // 上牌服务商id
//                'registration_province' => $k['registration_province'], //  上牌省份
//                'registration_city' => $k['registration_city'], // 上牌市
//                'transfer_export_id' => $k['transfer_export_id'] ? intval($k['transfer_export_id']) : 0, // 转移待出口服务商id
//                'transfer_export_province' => $k['transfer_export_province'], // 转移待出口省份
//                'transfer_export_city' => $k['transfer_export_city'], // 转移待出口上牌市
                'port_departure_charges' => $k['port_departure_charges'] ? round($k['port_departure_charges'], 2) : 0, // 起运港港杂费
                'international_freight' => $k['international_freight'] ? round($k['international_freight'], 2) : 0, // 国际运费
                'count' => $k['count'] ? round($k['count'], 2) : 0, // 数量
                'updated_at' => date('y-m-d h:m:s', time()), // 创建时间


                'sub_brand_name' => $k['sub_brand_name'], // 厂商
                'purchase_quotation' => $k['purchase_quotation'] ? round($k['purchase_quotation'], 2) : 0, // 行情报价
                'purchase_price' => $k['purchase_price'] ? round($k['purchase_price'], 2) : 0, // 二手车采购价格
                'VAT_invoice_price' => $k['VAT_invoice_price'] ? round($k['VAT_invoice_price'], 2) : 0, // 增值税发票金额
                'retail_concessions' => $k['retail_concessions'] ? round($k['retail_concessions'], 2) : 0, // 零售优惠
                'other_rebates' => $k['other_rebates'] ? round($k['other_rebates'], 2) : 0, // 采购返利
                'registration_fee' => $k['registration_fee'] ? round($k['registration_fee'], 2) : 0, //  上牌费用
                'used_car_fee' => $k['used_car_fee'] ? round($k['used_car_fee'], 2) : 0, //  二手车过户费用
                'transfer_export_fee' => $k['transfer_export_fee'] ? round($k['transfer_export_fee'], 2) : 0, // 转移待出口费用
                'total_price' => $k['total_price'] ? round($k['total_price'], 2) : 0,
                'premium_charges' => $k['premium_charges'] ? round($k['premium_charges'], 2) : 0,// 国际运输保险费
                'price_options' => json_encode($k['price_options']), // 费用选项
                'seat_count' => $k['seat_count'], // 座位数
                'car_year' => $k['car_year'], //  车辆年款
                'jb' => $k['jb'], // 级别
                'series_type' => $k['series_type'], // 车身类型
                'driver_form' => $k['driver_form'], // 驱动方式
                'length' => $k['length'], // 长
                'width' => $k['width'], // 宽
                'height' => $k['height'], // 高
                'curb_weight' => $k['curb_weight'], // 设计重量
                'resource_service_fee' => $k['resource_service_fee'], // 资源服务费
            ];

            if (array_key_exists('color_interior',$k)){
                $order_detail_data['color_interior'] = $k['color_interior']; // 内饰颜色
            }
            if (array_key_exists('color_exterior',$k)){
                $order_detail_data['color_exterior'] = $k['color_exterior']; // 外观颜色
            }


            if (array_key_exists('model_en',$k)){
                $order_detail_data['model_en'] = $k['model_en']; // 车型
            }
            if (array_key_exists('series_name_en',$k)){
                $order_detail_data['series_name_en'] = $k['series_name_en']; // 车系
            }
            if (array_key_exists('brands_name_en',$k)){
                $order_detail_data['brands_name_en'] = $k['brands_name_en']; // 品牌
            }
            if (array_key_exists('fuel_form_en',$k)){
                $order_detail_data['fuel_form_en'] = $k['fuel_form_en']; // 能源类型
            }
            if (array_key_exists('color_interior_en',$k)){
                $order_detail_data['color_interior_en'] = $k['color_interior_en']; // 内饰颜色
            }
            if (array_key_exists('color_exterior_en',$k)){
                $order_detail_data['color_exterior_en'] = $k['color_exterior_en']; // 外观颜色
            }
            if (array_key_exists('sub_brand_name_en',$k)){
                $order_detail_data['sub_brand_name_en'] = $k['sub_brand_name_en']; // 厂商
            }

            if (array_key_exists('is_drawback',$k)){
                $order_detail_data['is_drawback'] = $k['is_drawback']; // 是否退税
            }
            if (array_key_exists('is_CLIVTA',$k)){
                $order_detail_data['is_CLIVTA'] = $k['is_CLIVTA']; // 是否交强险  文森说的 要大些
            }

            if (array_key_exists('other_price',$k)){
                if ($k['other_price']){
                    $order_detail_data['other_price'] = json_encode($k['other_price']); // 其它费用
                }
            }
            if (array_key_exists('invoice_price',$k)){
                if ($k['invoice_price']){
                    $order_detail_data['invoice_price'] = $k['invoice_price']; // 机动车专用发票价
                }
            }




            $order_data['brands_name'] =  $order_data['brands_name'] . ' / ' . $k['brands_name'];
            $order_data['series_name'] =  $order_data['series_name'] . ' / ' . $k['series_name'];
            $order_data['model'] =  $order_data['model'] . ' / ' . $k['model'];
            $order_data['sub_brand_name'] =  $order_data['sub_brand_name'] . ' / ' . $k['sub_brand_name'];
//            $order_data['transfer_export_province'] =  $order_data['transfer_export_province'] . ' / ' . $k['transfer_export_province'];
            $including_model =  $k['brands_name'].'/'.$k['sub_brand_name'].'/'.$k['series_name'].'/'.$k['model'];
            array_push($order_data['including_model'],$including_model);

            $order_detail_id = WaOrdersQuotationRelevance::created($order_detail_data); // 创建订单详情
            if (!$order_detail_id) {
                return IndexController::error_by_static($order_detail_id, '创建子订单失败');
            }
        }

        if ($order_data['including_model']){
            $order_data['including_model'] = json_encode($order_data['including_model']);
        }

    }


    /**
     * 更新-报价单状态
     * @param Request $request
     * @return Response
     */
    public function updateQuotationOrderStatus(Request $request)
    {
//        process($request);
        $param = $request->all();

        $adminId = json_decode(adminId($request));

        // 查看订单状态
        $find = WaOrdersQuotation::find(['quotation_order_sn' => $param['quotation_order_sn']]);
        $find = json_decode($find);
        if (!$find) {
            return IndexController::errored('', '订单状态查询失败');
        }
        $status = $find->status; // 默认还是原来的状态
        \support\Db::beginTransaction();
        try {
            //报价单状态 验证 0 草稿 1 待客户确认 2 代下单 3 已完成 4已作废 5删除
            $check_status = OrderQuotationController::checkStatus($param,$status,$status_name);
            if ($check_status != 'true') {
                return IndexController::errored('', $check_status);
            }
            // 报价单状态更新
          $quotation_up = OrderQuotationController::ordersQuotationUp($param,$status);
            if ($quotation_up != 'true') {
                return IndexController::errored('', $quotation_up);
            }
            // 报价单操作日志添加
            $clounm = 'status由'.$find->status.'转变成'.$status.'('.$status_name.')';
            $describe = $adminId->nickname.'更新报价单状态'.$clounm.dateTime();
            $operate_log_add =  OrderQuotationController::operateLogAdd($param['quotation_order_sn'],$status,$adminId,$describe);
            if ($operate_log_add != 'true') {
                return IndexController::errored('', $operate_log_add);
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新成功');
        } catch (\Throwable $exception) {
            IndexController::logError('updateQuotationOrderStatus', $param, $adminId, $exception);

            // 回滚
            \support\Db::rollBack();

            return IndexController::errored($exception, '状态已更新失败');
        }

    }

    // 报价单状态
    public static function checkStatus($param,$status,&$status_name){
        //报价单状态 验证 0 草稿 1 待客户确认 2 代下单 3 已完成 4 已作废 5 删除
        $status_name = '';
        if ($param['status'] == 0) {
            return '报价单没有撤回草稿操作';
        } elseif (intval($param['status']) == 1) {
            if ($status != 0) {
                return '待客户确认状态已删除';
            }
            $status_name = '待客户确认';
        } elseif (intval($param['status']) == 2) {
            if ($status != 0) {
                return '只有回草状态下可更改';
            }
            $status_name = '待下单';
        } elseif (intval($param['status']) == 3) {
            // 只有待下单状态下才能生成订单  这个状态在销售订单创建接口修改
            return '生成订单/销售订单创建为同一接口';
        } elseif (intval($param['status']) == 4) {
            if (!in_array($status, [1, 2, 3])) {
                return '只有待客户确认 , 待下单, 已完成,状态下才能作废';
            }
            $status_name = '已作废';
        } elseif (intval($param['status']) == 5) {
            if ($status != 0) {
                return '只有草稿状态下才能删除';
            }
            $status_name = '删除';
        } else {
            return '不能修改此状态';
        }
        return 'true';
    }

    // 报价单操作日志添加
    public static function operateLogAdd($quotation_order_sn,$status,$adminId,$describe){
        $data_log = [
            'order_sn_parent' => $quotation_order_sn,
            'status' => $status,
            'describe' => $describe,
            'remark' => '',
            'reason' => '',
            'admin_id' => $adminId->id,
            'admin_name' => $adminId->nickname,
            'created_at' => dateTime(),
        ];
        $ordersOperateLog = WaOrdersQuotationOperateLog::created($data_log);
        if (!$ordersOperateLog) {
            return '报价单日志操作失败';
        }
        return  'true';
    }

    // 报价单状态更新
    public static function ordersQuotationUp($param,$status){
        $data_status = [
            'status' => intval($param['status']), // 报价单状态 0 草稿 1 待客户确认 2 待下单 3 已完成 4已作废 5删除
            'updated_at' => dateTime(),
        ];
        $where = [];
        $where [] = ['quotation_order_sn', '=', $param['quotation_order_sn']];
        $find = WaOrdersQuotation::find($where);
        $find = json_decode($find);
        if (!$find) {
            return '查不到订单信息';
        }
        if (intval($param['status']) == $status) {
            return '状态一致无需重复修改';
        }
        $up = WaOrdersQuotation::updated($data_status, $where);
        if (!$up) {
            return '订单状态更新失败';
        }
        return 'true';
    }


    /**
     * 报价单列表
     * @param Request $request
     * @return Response
     */
    public function quotationOrderList(Request $request)
    {
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $condition = [];
        $whereNotIn = [4,5];
        $up_between = [];
        $between = [];
        $sort = 1;
        // 数据权限 1 默认全部  2 只看自己
        if ($param['data_permission'] == 2) {
//            if ($adminId->data_permission == 2) {
                $condition [] = ['admin_id', '=', $adminId->id];
//            }
        }


        if ($param['quotation_order_sn']) {
            $condition [] = ['quotation_order_sn', 'like', '%' . $param['quotation_order_sn'] . '%'];
        }

        if (array_key_exists('currency',$param)){
            if ($param['currency']) {
                $condition [] = ['currency', '=', $param['currency']];
            }

        }



        if (array_key_exists('start_time',$param) && array_key_exists('end_time',$param)){
            if ($param['start_time'] && $param['end_time']){
                $between = between($param['start_time'], $param['end_time']);
            }
        }

        if (array_key_exists('up_start_time',$param) && array_key_exists('up_end_time',$param)){
            if ($param['up_start_time'] && $param['up_end_time']){
                $up_between = between($param['up_start_time'], $param['up_end_time']);
            }


        }

        if (array_key_exists('brands_name',$param)){
            if ($param['brands_name']){
                $condition [] = ['brands_name', 'like','%' . $param['brands_name'] . '%'];
            }
        }

        if (array_key_exists('series_name',$param)){
            if ($param['series_name']){
                $condition [] = ['series_name', 'like','%' . $param['series_name'] . '%'];
            }
        }

        if (array_key_exists('model',$param)){
            if ($param['model']){
                $condition [] = ['model', 'like','%' . $param['model'] . '%'];
            }
        }

        if (array_key_exists('sub_brand_name',$param)){
            if ($param['sub_brand_name']){
                $condition [] = ['sub_brand_name', 'like','%' . $param['sub_brand_name'] . '%'];
            }
        }

        if (array_key_exists('sort',$param)){
            if ($param['sort']){
                $sort = $param['sort'];
            }
        }



        $pageNum = pageNum($param['pageNum']);

        $page = page($param['page']);

        $fields = ['*'];


        // 验证有效期
       $check_exp =  OrderQuotationController::checkExp();
        if ($check_exp != 'true') {
            return IndexController::errored('', $check_exp);
        }
        $next_epartment_members = IndexController::nextDepartmentMembers($adminId);
        $whereIn = $next_epartment_members;
        $whereIn = []; // 报价单 现在有页面权限的都可以看到
        $listOrder = WaOrdersQuotation::list($page, $pageNum, $whereNotIn, $fields, $up_between, $sort,$whereIn, $condition, $between);
        return IndexController::successed($listOrder, '报价单列表');

    }

    public static function checkExp(){
        $condition = [];
        $que = WaOrdersQuotation::all($condition);
        $que = json_decode($que);

        if ($que){
            foreach ($que as $kq){
                $que_data = [
                    'updated_at' => dateTime()
                ];
                $que_where = [];

                if ($kq->exp_start_time){
                    $que_where [] = ['id','=',$kq->id];
                    $start_time = strtotime($kq->exp_start_time);
                    if ($start_time < time()){
                        //大于开始时间 需要判断结束时间
                        if ($kq->exp_end_time){
                            $end_time = strtotime($kq->exp_end_time);
                            if ($end_time < time()){
                                $que_data['exp_status'] = 2;
                            }
                        }
                    }
                }
                if ($kq->exp_end_time) {
                    $que_where [] = ['id','=',$kq->id];
                    $end_time = strtotime($kq->exp_end_time);
                    // 超出结束时间 -> 过期
                    if ($end_time < time()){
                        $que_data['exp_status'] = 2;
                    }
                }
                if ($que_where){
                    $que_up = WaOrdersQuotation::updated($que_data,$que_where);
                    if (!$que_up){
                        return '过期状态更新失败';
                    }
                }
            }
        }
        return 'true';
    }

    /**
     * 报价单产品信息
     * @param Request $request
     * @return Response
     */
    public function quotationOrderProducts(Request $request)
    {
        $param = $request->all();
        $condition = ['order_sn_parent' => $param['order_sn_parent']];
        $orderParentData = WaOrdersQuotation::find(['quotation_order_sn' => $param['order_sn_parent']]);
        if ($orderParentData) {
            $orderParentData = json_decode($orderParentData);
        } else {
            IndexController::errored('', '主订单信息获取失败');
        }

        $listOrder = [];// 当前订单的详情数据
        $quotationOrderChildren = WaOrdersQuotationRelevance::all($condition);
        $quotationOrderChildren = json_decode($quotationOrderChildren);
        if ($quotationOrderChildren) {
            $listOrder['quotationOrderChildren'] = $quotationOrderChildren;  // 当前订单子订单详情列表
            $listOrder['orderParentData'] = $orderParentData; //  当前订单主订单的详情信息
        }
        $listOrder = json_encode($listOrder);

        return IndexController::successed($listOrder, '报价单列表');
    }

    /**
     * 报价单删除 - 在报价单更新里面
     */

    /**
     * 报价单复制
     * @param Request $request
     * @return Response
     */
    public function quotationOrderCopy(Request $request){
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));

        $orderParentData = [];
        $orderChildData = [];
        $specs_can = [];

        // 获取主订单 和 子订单信息
        $data_get = OrderQuotationController::quotationOrderDataBySn($param,$orderParentData,$orderChildData,$specs_can);
        if ($data_get != 'true') {
            return IndexController::errored('', $data_get);
        }
        // 必传参数验证
        $order_quotation_add = OrderQuotationController::validateAdd($param, $adminId);
        if ($order_quotation_add != 'true') {
            return IndexController::errored('', $order_quotation_add);
        }


        $quotation_order_sn = 'WMBJF' . IndexController::generateOrderSnOther(); // 父订单编号

        // 获取报价单 账单明细 并替换 新的订单信息
       $amount_detail_change =  OrderQuotationController::amountDetailChange($param,$adminId,$quotation_order_sn);
        if ($amount_detail_change != 'true') {
            return IndexController::errored('', $amount_detail_change);
        }
        // 数据
       $data_by_copy =  OrderQuotationController::order_data_by_copy($quotation_order_sn,$param,$adminId,$order_data);
        if ($data_by_copy != 'true') {
            return IndexController::errored('',$data_by_copy );
        }
        if ($specs_can) {
            \support\Db::beginTransaction();
            try {
                $orders_id = WaOrdersQuotation::created($order_data); // 创建报价单
                if (!$orders_id) {
                    return IndexController::errored('', '创建报价单失败');
                }
                $specs = $specs_can;//车型信息

                foreach ($specs as $k) {
                    $k = get_object_vars($k);
                    $quotation_order_sn_child = 'WMBJZ' . IndexController::generateOrderSnOther(); // 子订单编号
                    OrderQuotationController::order_detail_data_create($quotation_order_sn,$quotation_order_sn_child,$k,$orders_id, $adminId);
                }

                //添加报价单账单明细
              $bill_details_create_by_copy = OrderQuotationController::bill_details_create_by_copy($quotation_order_sn,$param,$adminId);
                if ($bill_details_create_by_copy != 'true') {
                    return IndexController::errored('', $bill_details_create_by_copy);
                }

                \support\Db::commit();
                return IndexController::successed('', '报价单创建成功');
            } catch (\Throwable $exception) {

                IndexController::logError('quotationOrderCopy', $param, $adminId, $exception);

                // 回滚
                \support\Db::rollBack();

                return IndexController::errored($exception, '报价单创建失败');
            }

        } else {
            return IndexController::errored('', '创建报价单失败，参数值为空');
        }
    }

    // 获取主订单 和 子订单信息 - copy
    public static function quotationOrderDataBySn(&$param,&$orderParentData,&$orderChildData,&$specs_can){
        // 报价单 信息获取
        $orderParentData = WaOrdersQuotation::find(['quotation_order_sn' => $param['quotation_order_sn']]);
        if ($orderParentData) {
            $orderParentData = json_decode($orderParentData);
        } else {
            return '主订单信息获取失败';
        }

        // 报价单子订单数据获取
        $orderChildData = WaOrdersQuotationRelevance::all(['order_sn_parent' => $param['quotation_order_sn']]);
        if ($orderParentData) {
            $orderChildData = json_decode($orderChildData);
            foreach ($orderChildData as $kcld){
                $order_sn_child = 'WMBJZ' . IndexController::generateOrderSnOther(); // 子订单编号
                $kcld->order_sn_child = $order_sn_child;
            }

            $specs_can = $orderChildData;
        } else {
            return '主订单信息获取失败';
        }
        $param = [
            'quotation_order_sn' => $param['quotation_order_sn'],
//            'user_id' => $orderParentData->user_id,
            'pol' => $orderParentData->pol,
            'pod' => $orderParentData->pod,
            'pol_en' => $orderParentData->pol_en,
            'pod_en' => $orderParentData->pod_en,
            'cnh' => $orderParentData->cnh,
            'condition' => $orderParentData->condition,
            'currency' => $orderParentData->currency,
            'shipment' => $orderParentData->shipment,
            'brands_name' => $orderParentData->brands_name, //
            'series_name' => $orderParentData->series_name, //
            'model' => $orderParentData->model, // 交货条件
            'sub_brand_name' => $orderParentData->sub_brand_name, //

            'specs_can' => $specs_can,
            'bill_details' => [],
        ];
        return 'true';

    }

    // 数据 - copy
    public static function order_data_by_copy($order_sn,$param,$adminId,&$order_data){
        $order_data = [
            'quotation_order_sn' => $order_sn,

            'pol' => $param['pol'], // POL装港
            'pod' => $param['pod'], // POD卸港
            'pol_en' => $param['pol_en'],
            'pod_en' => $param['pod_en'],
            'cnh' => $param['cnh'], // 美元汇率
            'condition' => $param['condition'], // 交货条件

            'status' => 0, //报价单状态 0 草稿 1 待客户确认 2 待下单 3 已完成 4 删除 5作废
            'created_at' => date('y-m-d h:m:s', time()), // 创建时间
            'admin_id' => $adminId->id, // 管理员名称
            'admin_name' => $adminId->nickname, // 管理员名称
            'currency' => $param['currency'], // 货币类型   1人民币 2 美元 3 欧元
            'shipment' => $param['shipment'], // 1 汽运、2 铁路、海运(3 集装箱、4滚装船)

            'brands_name' => $param['brands_name'], //
            'series_name' => $param['series_name'], //
            'model' => $param['model'], // 交货条件
            'sub_brand_name' => $param['sub_brand_name'], //
//            'transfer_export_province' => $param['transfer_export_province'], //

        ];
        return 'true';
    }

    // 账单明细数据-copy
    public static function bill_details_create_by_copy($quotation_order_sn,$param,$adminId){
        $bill_details = $param['bill_details'];
        if ($bill_details) {
            foreach ($bill_details as $kd) {
                $bill_details_data = [
                    'quotation_order_sn' => $quotation_order_sn, //
                    'total_amount' => $kd['total_amount'], //
                    'price_name' => $kd['price_name'], //
                    'admin_id' => $adminId->id, //
                    'admin_name' => $adminId->nickname, //
                    'created_at' => dateTime(), //
                ];

                $bill_details_id = WaOrdersQuotationAmountDetail::created($bill_details_data); // 创建订单详情
                if (!$bill_details_id) {
                    return '添加采购订单账单明细失败';
                }
            }
        } else {
            return '采购费用，参数值为空';
        }
        return 'true';
    }

    // 账单明细数据更改-copy
    public static function amountDetailChange(&$param,$adminId,$quotation_order_sn){
        $bill_details = [];
        $amount_condition= [];
        $amount_condition [] = ['quotation_order_sn','=', $param['quotation_order_sn']];
        $quotation_amount_detail = WaOrdersQuotationAmountDetail::all($amount_condition);
        if ($quotation_amount_detail) {
            $quotation_amount_detail = json_decode($quotation_amount_detail);
            foreach ($quotation_amount_detail as $kq){
                $qad_data = [
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'total_amount' => $kq->total_amount,
                    'price_name' => $kq->price_name,
                    'quotation_order_sn' => $quotation_order_sn,
                    'created_at' => dateTime(),
                ];
                array_push($bill_details,$qad_data);

            }

        } else {
            return '主订单信息获取失败';
        }
        $param['bill_details'] = $bill_details;
        return 'true';
    }

}